package com.yinxing.webapi.code.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yinxing.framework.domain.R;
import com.yinxing.webapi.code.entity.sys.SysTable;
import com.yinxing.webapi.code.service.sys.ISysTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/SysTableController")
public class SysTableController {

    @Autowired
    private ISysTableService service;

    /**
     * 分页查询
     * @param page 分页模型(url?page=1&limit=20)
     * @param params 查询参数 url?page=1&limit=20&key1=value1&key2=value2
     */
    @GetMapping("/selectPage")
    public R selectPage(Page<SysTable> page, @RequestParam Map<String, String> params) {
        QueryWrapper<SysTable> qw = new QueryWrapper<>();
        final String queryParam = "QueryParam_";
        if(params != null && params.containsKey(queryParam)) {
            String queryParamValue = params.get(queryParam);
            qw.eq("TableName_", queryParamValue)
                .or().eq("Package_", queryParamValue)
                .or().eq("ModelName_", queryParamValue);
        }
        service.syncTableList();
        IPage<SysTable> iPage = service.selectPage(page, qw);
        return R.ok(iPage);
    }

    /**
     * 主键查询
     * @param id 主键
     */
    @GetMapping("/selectById")
    public R selectById(long id) {
        SysTable record = service.selectById(id);
        return R.ok(record);
    }

    /**
     * 新增|更新
     * @param record 实体类
     */
    @PostMapping("/insertOrUpdate")
    public R insertOrUpdate(SysTable record) {
        if(record.getId_() != null) {
            service.updateById(record);
        } else {
            service.insert(record);
        }
        return R.ok();
    }

    /**
     * 删除
     * @param id 主键
     */
    @PostMapping("/deleteById")
    public R deleteById(@RequestParam long id) {
        service.deleteMeAndColumns(id);
        return R.ok();
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam Long tableId) throws Exception {
        byte[] data = service.downloadCode(tableId);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"yinxing.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
